<template>
  <div class="message-flow-test">
    <div class="test-header">
      <h1>消息业务完整流程测试</h1>
      <p>测试从房源详情联系房东到消息收发的完整流程</p>
    </div>

    <div class="test-content">
      <!-- 测试步骤 -->
      <div class="test-steps">
        <el-steps :active="currentStep" finish-status="success">
          <el-step title="用户登录" description="登录系统获取用户信息"></el-step>
          <el-step title="WebSocket连接" description="建立实时消息连接"></el-step>
          <el-step title="创建聊天会话" description="模拟从房源详情联系房东"></el-step>
          <el-step title="发送聊天消息" description="发送测试消息"></el-step>
          <el-step title="接收消息推送" description="验证实时消息推送"></el-step>
          <el-step title="系统通知测试" description="测试系统通知功能"></el-step>
          <el-step title="消息状态管理" description="测试已读/未读状态"></el-step>
        </el-steps>
      </div>

      <!-- 测试控制面板 -->
      <div class="test-controls">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>测试控制</span>
              <el-button type="primary" @click="runFullTest" :loading="testing">
                运行完整测试
              </el-button>
            </div>
          </template>

          <div class="control-buttons">
            <el-button @click="testLogin" :loading="loading.login">1. 测试登录</el-button>
            <el-button @click="testWebSocket" :loading="loading.websocket">2. 测试WebSocket</el-button>
            <el-button @click="testCreateSession" :loading="loading.session">3. 创建会话</el-button>
            <el-button @click="testSendMessage" :loading="loading.message">4. 发送消息</el-button>
            <el-button @click="testSystemNotification" :loading="loading.notification">5. 系统通知</el-button>
            <el-button @click="testMessageState" :loading="loading.state">6. 消息状态</el-button>
            <el-button @click="clearResults" type="warning">清空结果</el-button>
          </div>
        </el-card>
      </div>

      <!-- 测试状态显示 -->
      <div class="test-status">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card>
              <template #header>用户状态</template>
              <div class="status-item">
                <span>登录状态:</span>
                <el-tag :type="userInfo ? 'success' : 'danger'">
                  {{ userInfo ? '已登录' : '未登录' }}
                </el-tag>
              </div>
              <div class="status-item" v-if="userInfo">
                <span>用户ID:</span>
                <span>{{ userInfo.id }}</span>
              </div>
              <div class="status-item" v-if="userInfo">
                <span>用户名:</span>
                <span>{{ userInfo.username }}</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card>
              <template #header>WebSocket状态</template>
              <div class="status-item">
                <span>连接状态:</span>
                <el-tag :type="wsConnected ? 'success' : 'danger'">
                  {{ wsConnected ? '已连接' : '未连接' }}
                </el-tag>
              </div>
              <div class="status-item">
                <span>消息处理器:</span>
                <span>{{ messageHandlerCount }}</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card>
              <template #header>消息状态</template>
              <div class="status-item">
                <span>系统未读:</span>
                <el-badge :value="systemUnreadCount" class="badge-item">
                  <span>系统消息</span>
                </el-badge>
              </div>
              <div class="status-item">
                <span>聊天未读:</span>
                <span>{{ chatUnreadCount }}</span>
              </div>
              <div class="status-item">
                <span>总未读:</span>
                <el-badge :value="totalUnreadCount" class="badge-item">
                  <span>总计</span>
                </el-badge>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 测试结果 -->
      <div class="test-results">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>测试结果</span>
              <el-tag :type="allTestsPassed ? 'success' : 'warning'">
                {{ allTestsPassed ? '全部通过' : '部分失败' }}
              </el-tag>
            </div>
          </template>

          <div class="results-list">
            <div 
              v-for="(result, index) in testResults" 
              :key="index"
              class="result-item"
              :class="{ success: result.success, error: !result.success }"
            >
              <div class="result-header">
                <el-icon v-if="result.success" color="green"><SuccessFilled /></el-icon>
                <el-icon v-else color="red"><CircleCloseFilled /></el-icon>
                <span class="result-title">{{ result.title }}</span>
                <span class="result-time">{{ result.timestamp }}</span>
              </div>
              <div class="result-description">{{ result.description }}</div>
              <div v-if="result.data" class="result-data">
                <el-collapse>
                  <el-collapse-item title="详细数据">
                    <pre>{{ JSON.stringify(result.data, null, 2) }}</pre>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 实时消息日志 -->
      <div class="message-log">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>实时消息日志</span>
              <el-button size="small" @click="clearMessageLog">清空日志</el-button>
            </div>
          </template>

          <div class="log-list">
            <div 
              v-for="(log, index) in messageLogs" 
              :key="index"
              class="log-item"
              :class="log.type"
            >
              <span class="log-time">{{ log.timestamp }}</span>
              <span class="log-type">{{ log.type.toUpperCase() }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import { 
  userLogin, 
  createChatSession, 
  sendChatMessage,
  getSystemMessages,
  markSystemMessageRead
} from '@/utils/apiService'
import { getUserInfo, saveUserToken, saveUserInfo } from '@/utils/auth'
import chatWebSocket from '@/utils/websocket'
import messageStateManager from '@/utils/messageStateManager'

// 响应式数据
const currentStep = ref(0)
const testing = ref(false)
const userInfo = ref(null)
const wsConnected = ref(false)
const messageHandlerCount = ref(0)
const testResults = ref([])
const messageLogs = ref([])

const loading = reactive({
  login: false,
  websocket: false,
  session: false,
  message: false,
  notification: false,
  state: false
})

// 使用全局状态管理器的数据
const systemUnreadCount = messageStateManager.systemUnreadCount
const chatUnreadCount = ref(0)
const totalUnreadCount = computed(() => messageStateManager.getTotalUnreadCount())

// 计算属性
const allTestsPassed = computed(() => {
  return testResults.value.length > 0 && testResults.value.every(r => r.success)
})

// 添加测试结果
const addTestResult = (title, description, success, data = null) => {
  testResults.value.push({
    title,
    description,
    success,
    data,
    timestamp: new Date().toLocaleTimeString()
  })
}

// 添加消息日志
const addMessageLog = (type, message) => {
  messageLogs.value.unshift({
    type,
    message,
    timestamp: new Date().toLocaleTimeString()
  })
  
  // 限制日志数量
  if (messageLogs.value.length > 100) {
    messageLogs.value = messageLogs.value.slice(0, 100)
  }
}

// 清空结果
const clearResults = () => {
  testResults.value = []
  currentStep.value = 0
}

// 清空消息日志
const clearMessageLog = () => {
  messageLogs.value = []
}

// 1. 测试登录
const testLogin = async () => {
  loading.login = true
  try {
    addMessageLog('info', '开始测试用户登录...')
    
    const loginData = {
      username: 'testuser',
      password: 'password123'
    }
    
    const response = await userLogin(loginData)
    
    if (response.data.code === 200 || response.data.code === '200') {
      const userData = response.data.data
      saveUserToken(userData.token)
      saveUserInfo(userData.user)
      userInfo.value = userData.user
      
      addTestResult('用户登录', '登录成功', true, userData)
      addMessageLog('success', `用户 ${userData.user.username} 登录成功`)
      currentStep.value = Math.max(currentStep.value, 1)
    } else {
      throw new Error(response.data.message || '登录失败')
    }
  } catch (error) {
    addTestResult('用户登录', `登录失败: ${error.message}`, false, error)
    addMessageLog('error', `登录失败: ${error.message}`)
  } finally {
    loading.login = false
  }
}

// 2. 测试WebSocket连接
const testWebSocket = async () => {
  loading.websocket = true
  try {
    addMessageLog('info', '开始测试WebSocket连接...')
    
    await chatWebSocket.connect()
    wsConnected.value = true
    
    // 添加测试消息处理器
    chatWebSocket.addMessageHandler('test-handler', (message) => {
      addMessageLog('websocket', `收到聊天消息: ${JSON.stringify(message)}`)
    })
    
    chatWebSocket.addUnreadHandler('test-unread', (unreadData) => {
      addMessageLog('websocket', `未读数量更新: ${JSON.stringify(unreadData)}`)
    })
    
    chatWebSocket.addNotificationHandler('test-notification', (notification) => {
      addMessageLog('websocket', `收到系统通知: ${JSON.stringify(notification)}`)
    })
    
    messageHandlerCount.value = 3
    
    addTestResult('WebSocket连接', 'WebSocket连接成功', true)
    addMessageLog('success', 'WebSocket连接建立成功')
    currentStep.value = Math.max(currentStep.value, 2)
  } catch (error) {
    addTestResult('WebSocket连接', `连接失败: ${error.message}`, false, error)
    addMessageLog('error', `WebSocket连接失败: ${error.message}`)
  } finally {
    loading.websocket = false
  }
}

// 3. 测试创建聊天会话
const testCreateSession = async () => {
  loading.session = true
  try {
    addMessageLog('info', '开始测试创建聊天会话...')
    
    const sessionData = {
      targetUserId: 2, // 假设目标用户ID为2
      houseId: 1 // 假设房源ID为1
    }
    
    const response = await createChatSession(sessionData)
    
    if (response.data.code === 200 || response.data.code === '200') {
      addTestResult('创建聊天会话', '会话创建成功', true, response.data.data)
      addMessageLog('success', `聊天会话创建成功，会话ID: ${response.data.data.sessionId}`)
      currentStep.value = Math.max(currentStep.value, 3)
    } else {
      throw new Error(response.data.message || '创建会话失败')
    }
  } catch (error) {
    addTestResult('创建聊天会话', `创建失败: ${error.message}`, false, error)
    addMessageLog('error', `创建聊天会话失败: ${error.message}`)
  } finally {
    loading.session = false
  }
}

// 4. 测试发送消息
const testSendMessage = async () => {
  loading.message = true
  try {
    addMessageLog('info', '开始测试发送聊天消息...')
    
    const messageData = {
      receiverId: 2,
      content: `测试消息 - ${new Date().toLocaleString()}`,
      type: 1
    }
    
    // 通过WebSocket发送消息
    if (wsConnected.value) {
      chatWebSocket.sendMessage(messageData)
      addTestResult('发送聊天消息', 'WebSocket消息发送成功', true, messageData)
      addMessageLog('success', `通过WebSocket发送消息: ${messageData.content}`)
    } else {
      // 通过REST API发送消息
      const response = await sendChatMessage(messageData)
      
      if (response.data.code === 200 || response.data.code === '200') {
        addTestResult('发送聊天消息', 'REST API消息发送成功', true, response.data.data)
        addMessageLog('success', `通过REST API发送消息: ${messageData.content}`)
      } else {
        throw new Error(response.data.message || '发送消息失败')
      }
    }
    
    currentStep.value = Math.max(currentStep.value, 4)
  } catch (error) {
    addTestResult('发送聊天消息', `发送失败: ${error.message}`, false, error)
    addMessageLog('error', `发送聊天消息失败: ${error.message}`)
  } finally {
    loading.message = false
  }
}

// 5. 测试系统通知
const testSystemNotification = async () => {
  loading.notification = true
  try {
    addMessageLog('info', '开始测试系统通知功能...')
    
    // 获取系统消息
    const response = await getSystemMessages({ page: 1, size: 5 })
    
    if (response.data.code === 200 || response.data.code === '200') {
      const messages = response.data.data.messages || []
      addTestResult('系统通知', `获取到 ${messages.length} 条系统消息`, true, messages)
      addMessageLog('success', `成功获取 ${messages.length} 条系统消息`)
      currentStep.value = Math.max(currentStep.value, 5)
    } else {
      throw new Error(response.data.message || '获取系统消息失败')
    }
  } catch (error) {
    addTestResult('系统通知', `测试失败: ${error.message}`, false, error)
    addMessageLog('error', `系统通知测试失败: ${error.message}`)
  } finally {
    loading.notification = false
  }
}

// 6. 测试消息状态管理
const testMessageState = async () => {
  loading.state = true
  try {
    addMessageLog('info', '开始测试消息状态管理...')
    
    // 刷新未读数量
    await messageStateManager.refreshSystemUnreadCount()
    
    addTestResult('消息状态管理', '状态管理功能正常', true, {
      systemUnreadCount: systemUnreadCount.value,
      totalUnreadCount: totalUnreadCount.value
    })
    addMessageLog('success', `消息状态管理测试完成，系统未读: ${systemUnreadCount.value}`)
    currentStep.value = Math.max(currentStep.value, 6)
  } catch (error) {
    addTestResult('消息状态管理', `测试失败: ${error.message}`, false, error)
    addMessageLog('error', `消息状态管理测试失败: ${error.message}`)
  } finally {
    loading.state = false
  }
}

// 运行完整测试
const runFullTest = async () => {
  testing.value = true
  clearResults()
  
  try {
    addMessageLog('info', '开始运行完整消息流程测试...')
    
    await testLogin()
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await testWebSocket()
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await testCreateSession()
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await testSendMessage()
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await testSystemNotification()
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await testMessageState()
    
    addMessageLog('success', '完整消息流程测试完成')
    ElMessage.success('完整测试流程执行完毕')
  } catch (error) {
    addMessageLog('error', `完整测试失败: ${error.message}`)
    ElMessage.error('测试过程中出现错误')
  } finally {
    testing.value = false
  }
}

// 生命周期
onMounted(() => {
  // 检查当前登录状态
  const currentUser = getUserInfo()
  if (currentUser) {
    userInfo.value = currentUser
    currentStep.value = 1
  }
  
  // 检查WebSocket连接状态
  wsConnected.value = chatWebSocket.isConnected()
  
  addMessageLog('info', '消息流程测试页面已加载')
})

onBeforeUnmount(() => {
  // 清理测试处理器
  chatWebSocket.removeMessageHandler('test-handler')
  chatWebSocket.removeUnreadHandler('test-unread')
  chatWebSocket.removeNotificationHandler('test-notification')
})
</script>

<style scoped>
.message-flow-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-header {
  text-align: center;
  margin-bottom: 30px;
}

.test-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.test-header p {
  color: #7f8c8d;
  font-size: 16px;
}

.test-steps {
  margin-bottom: 30px;
}

.test-controls {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.control-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.test-status {
  margin-bottom: 30px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.badge-item {
  margin-left: 10px;
}

.test-results {
  margin-bottom: 30px;
}

.results-list {
  max-height: 400px;
  overflow-y: auto;
}

.result-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 10px;
}

.result-item.success {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.result-item.error {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.result-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.result-title {
  font-weight: bold;
  margin-left: 8px;
  flex: 1;
}

.result-time {
  color: #909399;
  font-size: 12px;
}

.result-description {
  color: #606266;
  margin-bottom: 8px;
}

.result-data pre {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 200px;
  overflow: auto;
}

.message-log {
  margin-bottom: 30px;
}

.log-list {
  max-height: 300px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.log-item {
  padding: 5px 10px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.log-item.info {
  background-color: #f0f9ff;
}

.log-item.success {
  background-color: #f0f9ff;
  color: #67c23a;
}

.log-item.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.log-item.websocket {
  background-color: #f9f0ff;
  color: #722ed1;
}

.log-time {
  color: #909399;
  margin-right: 10px;
  min-width: 80px;
}

.log-type {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}

.log-message {
  flex: 1;
}
</style>
